package main

import (
	"MqttCloudProtocolServer/WebServer/webapi"
	"MqttCloudProtocolServer/publiclib/logiclib"
	"net/http"

	"github.com/wonderivan/logger"
)

type webServer struct {
	server       *http.Server
	templatePath string
}

func (_this *webServer) Start(templateDir string) {
	println(templateDir)
	_this.templatePath = templateDir
	mux := http.NewServeMux()
	new(webapi.GatewayServerManagerService).Regist(mux)
	new(webapi.ServiceControlService).Regist(mux)
	new(webapi.LogfileService).Regist(mux)
	new(webapi.ServerWatchManagerService).Regist(mux)
	new(webapi.GatewayWatcherService).Regist(mux)
	new(webapi.UserLoginService).Regist(mux)
	new(webapi.UserManagerService).Regist(mux)
	new(webapi.DbCleanService).Regist(mux)
	new(webapi.UpdateGatewayService).Regist(mux)
	mux.HandleFunc("/", _this.FileFilterServe)
	//mux.Handle("/conf/", http.StripPrefix("/conf/", http.FileServer(http.Dir("config"))))

	cfgManager := new(logiclib.ConfigFileBase)
	confs := cfgManager.LoadPortCfg()
	port, res := cfgManager.GetValueFromKey(confs, "web")
	if !res {
		port = "8089"
	}
	_this.server = &http.Server{Addr: "0.0.0.0:" + port}
	_this.server.Handler = mux
	if err := _this.server.ListenAndServe(); err != nil {
		logger.Alert(err)
	}
	//if err := _this.server.ListenAndServeTLS("config/server2.crt", "config/server.key"); err != nil {
	//	logger.Alert(err)
	//}
}

func (_this *webServer) FileFilterServe(w http.ResponseWriter, r *http.Request) {
	//拦截登录信息在这里做
	h := http.FileServer(http.Dir(_this.templatePath))
	h.ServeHTTP(w, r)
}

func (_this *webServer) Stop() {
	_this.server.Close()
}
